package cc.laop.netty.server;

import cc.laop.netty.entity.AskMsg;
import cc.laop.netty.entity.BaseMsg;
import cc.laop.netty.entity.LoginMsg;
import cc.laop.netty.entity.PingMsg;
import cc.laop.netty.entity.ReplyMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;

public class NettyServerHandler extends SimpleChannelInboundHandler<BaseMsg> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, BaseMsg msg)
			throws Exception {

		switch (msg.getMsgType()) {
		case LOGIN:
			login(ctx, msg);
			break;
		case ASK:
			ask(ctx, msg);
			break;
		case REPLY:
			reply(ctx, msg);
			break;
		case PING:
			ping(ctx, msg);
			break;
		default:
			break;
		}

	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		super.channelInactive(ctx);
		ChannelManager.remove((SocketChannel) ctx.channel());
		System.out.println("Client inactive.");
	}

	public void login(ChannelHandlerContext ctx, BaseMsg msg) {
		LoginMsg lm = (LoginMsg) msg;
		System.out.println("Login System: " + lm.getUserid());
		ChannelManager.add(lm.getChannelid(), (SocketChannel) ctx.channel());
	}

	public void ask(ChannelHandlerContext ctx, BaseMsg msg) {
		AskMsg am = (AskMsg) msg;
		System.out.println("Ask: " + am.getMessage());

		ReplyMsg pm = new ReplyMsg();
		pm.setMessage("reply for ask: " + am.getMessage());
		ctx.channel().writeAndFlush(pm);
	}

	public void reply(ChannelHandlerContext ctx, BaseMsg msg) {
		ReplyMsg rm = (ReplyMsg) msg;
		System.out.println("Reply: " + rm.getMessage());
	}

	public void ping(ChannelHandlerContext ctx, BaseMsg msg) {
		PingMsg pm = (PingMsg) msg;
		ctx.channel().writeAndFlush(pm);
	}

}
